/*
 * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * This file is part of Harmattan SmashMiner OpenGL game application.
 * 
 * Harmattan SmashMiner OpenGL Example Application version 1.0.0
 *  
 * Latest update: 15.4.2011
 *
 * The Harmattan SmashMiner OpenGL example application demonstrates how to use 
 * the OpenGL ES in Harmattan devices.
 *
 * This example is provided as a starting point for 3rd party
 * developers (you) to ease the implementation of OpenGL based 
 * games. Ideas, parts of code or methodologies that this
 * example application uses can be freely used without restrictions.
 *
 * See file README.txt how to build and compile this example application
 * in the Harmattan SDK environment. 
 * 
 * See file INSTALL.txt to find out what is required to run this
 * application and how to install the application to the device or
 * alternatively in QEMU-emulator.
 *
 * The LICENSE.txt file explains the license this software is provided
 * with. A copy of the same license is included in this source file.
 * 
 */

/*
 * Copyright (C) 2011 by Nokia Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "hyperjumpnavigator.h"

#include "asteroid.h"
#include "collectible.h"
#include "blackhole.h"
#include "comet.h"

#include <QDebug>

/*!
  \class HyperJumpDestination
  Container for SpaceCraft hyper jump out destination.
*/

/*!
  Constructs the destination with initial values.
*/
HyperJumpDestination::HyperJumpDestination() 
    : posX(0.0f)
    , posY(0.0f)
    , rounds(0)
    , score(0.0f)
    , changeX(0.0f)
    , changeY(0.0f)
{
}

/*!
  \class HyperJumpNavigator
  To calculate the best position for hyper jump out. Best position is where the miner is as safe as possible when coming back to game screen.

  \par Evaluating the best hyperjump postition
At first the three initial hyperjump destinations are created.
Destinations are created at the vertical center of screen to X coordinates 0, -X range/2 and X range/2.

These three places are refined within each frame of the game until target time is reached.
Refine algorithm tries to estimate positions of the game objects at the target time and the miner dodges away from their position.
Defines \c #CHANGE_RATE and \c #MAX_CHANGE can be changed to tune calculation for best position.

Each position has score and best position of the three is which has lowes score. Score is calculated by the positions of the game objects.
*/

/*!
  Constructs the hyper jump navigator.

  \a targetTime Target time of the calculation.

  \a viewRangeX X range of game area.

  \a viewRangeY Y range of game area.
*/
HyperJumpNavigator::HyperJumpNavigator(FPtype targetTime, FPtype viewRangeX, FPtype viewRangeY) 
    : storedTargetTime(targetTime)
    , taskSwitcher(0)
    , timeLeft(0.0f)
    , dest(NULL)
    , gameViewRangeX(viewRangeX)
    , gameViewRangeY(viewRangeY)
{
    // generate initial guess destinations.
    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    HyperJumpDestination * dest;

    dest = new HyperJumpDestination;
    dest->posX = 0.0f;
    dest->posY = 0.0f;
    dest->rounds = 0;
    dest->score = 0.0f;
    destList.append(dest);

    dest = new HyperJumpDestination;
    dest->posX = +0.50f * gameViewRangeX;
    dest->posY = 0.0f;
    dest->rounds = 0;
    dest->score = 0.0f;
    destList.append(dest);

    dest = new HyperJumpDestination;
    dest->posX = -0.50f * gameViewRangeX;
    dest->posY = 0.0f;
    dest->rounds = 0;
    dest->score = 0.0f;
    destList.append(dest);
}

/*!
  Destructs \c HyperJumpNavigator. Deletes destinations and clears.
*/
HyperJumpNavigator::~HyperJumpNavigator()
{
    for (int i = 0;i < destList.count();i++)
        delete destList.at(i);

    destList.clear();
}

/*!
  Refines the \c HyperJumpDestination calculations within the current time frame.
*/
void HyperJumpNavigator::refine(FPtype currentTime,
                                QList<Asteroid*> &asteroidList,
                                QList<Collectible*> &collectibleList,
                                QList<GameObject*> &enemyList,
                                BlackHole *blackhole,
                                Comet * comet)
{
    timeLeft = storedTargetTime - currentTime;

    if (timeLeft < 0.0f) {
#ifdef SMASHMINER_CONFIG_ENABLE_DEBUG_CHECKS
        qDebug() << "WARNING : HyperJumpNavigator::refine() called past targetTime.";
#endif  // SMASHMINER_CONFIG_ENABLE_DEBUG_CHECKS
        return;
    }

    dest = destList.at(taskSwitcher);

    dest->rounds++;
    dest->score = 0.0f;
    dest->changeX = 0.0f;
    dest->changeY = 0.0f;

    // process all objects:
    // -> the score is computed.
    // -> the destination is refined.

    for (int i = 0;i < asteroidList.count();i++) {
        Asteroid *a = asteroidList.at(i);
        if (!a->isAlive()) continue;
        process((GameObject *) a, 2.0f, true);
    }

    for (int i = 0;i < collectibleList.count();i++) {
        Collectible *c = collectibleList.at(i);
        if (!c->isAlive()) continue;
        process((GameObject *) c, 1.0f, true);
    }

    for (int i = 0;i < enemyList.count();i++) {
        GameObject *go = enemyList.at(i);
        if (!go->isAlive()) continue;
        process(go, 2.0f, false);
    }

    if (blackhole != NULL && blackhole->isAlive())
        process((GameObject *) blackhole, 8.0f, false);

    if (comet != NULL && comet->isAlive())
        process((GameObject *) comet, 4.0f, false);

    // apply the change to destination.
    // keep the destinations at valid range.

    dest->posX += dest->changeX;
    dest->posY += dest->changeY;

    const FPtype limitX = 0.80f * gameViewRangeX;
    const FPtype limitY = 0.80f * gameViewRangeY;

    if (dest->posX < -limitX) dest->posX = -limitX;
    if (dest->posX > +limitX) dest->posX = +limitX;

    if (dest->posY < -limitY) dest->posY = -limitY;
    if (dest->posY > +limitY) dest->posY = +limitY;

    // cycle the task switcher...
    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    if (++taskSwitcher >= destList.count())
        taskSwitcher = 0;
}

/*!
  Gets the best \a HyperJumpDestination.
*/
void HyperJumpNavigator::getBest(HyperJumpDestination & dest)
{
    HyperJumpDestination *best = destList.front();

    // now we have picked up the first destination as a best one.
    // check others against the best known destination...
    // NOTE : lowest score = best solution!!!

    for (int i = 1;i < destList.count();i++) {
        if (destList.at(i)->rounds < 1)
            continue;

        if (destList.at(i)->score < best->score)
            best = destList.at(i);
    }

    // now return the best destination.

    dest.posX = (*best).posX;
    dest.posY = (*best).posY;
    dest.rounds = (*best).rounds;
    dest.score = (*best).score;
}

/*!
  Gets the \c HyperJumpDestination from the given \a index.
*/
HyperJumpDestination * HyperJumpNavigator::getAtIndex(int index)
{
    if (index > -1 && index < destList.count())
        return destList.at(index);
    else
        return NULL;
}

/*!
 Process calculation for single GameObject \a object.
*/
void HyperJumpNavigator::process(GameObject *object, FPtype weight, bool wrapping)
{
#ifdef SMASHMINER_CONFIG_ENABLE_DEBUG_CHECKS

    if (!object->isAlive()) {
        qDebug() << "HyperJumpNavigator::process() : object is dead.";
        exit(EXIT_FAILURE);
    }

#endif  // SMASHMINER_CONFIG_ENABLE_DEBUG_CHECKS

    // integrate object motion:
    // see GameEngine::integrateMotion().

    FPtype objX = object->posX();
    objX = objX + object->velX() * timeLeft * 5.0f; // This will calculate the target position of the object in the future

    FPtype objY = object->posY();
    objY = objY + object->velY() * timeLeft * 5.0f; // This will calculate the target position of the object in the future

    if (wrapping) {
        // Check wrappings if wrapping object
        if (objX > gameViewRangeX)
            objX = objX - 2.0f * gameViewRangeX;
        else if (objX < -gameViewRangeX)
            objX = objX + 2.0f * gameViewRangeX;

        if (objY > gameViewRangeY)
            objY = objY - 2.0f * gameViewRangeY;
        else if (objY < -gameViewRangeY)
            objY = objY + 2.0f * gameViewRangeY;
    }

    // compute a vector from object to destination.
    FPtype vectX = dest->posX - objX;
    FPtype vectY = dest->posY - objY;
    if (wrapping) {
        // Calculate shortest X and Y distances to wrapping objects
        if (vectX > +gameViewRangeX) {
            FPtype objWrapX = -(gameViewRangeX + (gameViewRangeX - objX));
            vectX = dest->posX - objWrapX;
        }
        else if (vectX < -gameViewRangeX) {
            FPtype objWrapX = gameViewRangeX + (gameViewRangeX + objX);
            vectX = dest->posX - objWrapX;
        }
        if (vectY > +gameViewRangeY) {
            FPtype objWrapY = -(gameViewRangeY + (gameViewRangeY - objY));
            vectY = dest->posY - objWrapY;
        }
        else if (vectY < -gameViewRangeY) {
            FPtype objWrapY = gameViewRangeY + (gameViewRangeY + objY);
            vectY = dest->posY - objWrapY;
        }
    }

    // compute vector length and destination score.
    // make sure that we never go in a "division by zero" situation.

    const FPtype vectLen2 = vectX * vectX + vectY * vectY + 0.10f;
    dest->score += weight / vectLen2; // high distance = low score...

    FPtype changeX = CHANGE_RATE * vectX / vectLen2;
    if (changeX > +MAX_CHANGE) changeX = +MAX_CHANGE;
    if (changeX < -MAX_CHANGE) changeX = -MAX_CHANGE;

    FPtype changeY = CHANGE_RATE * vectY / vectLen2;
    if (changeY > +MAX_CHANGE) changeY = +MAX_CHANGE;
    if (changeY < -MAX_CHANGE) changeY = -MAX_CHANGE;

    dest->changeX += changeX;
    dest->changeY += changeY;
}
